<?php
if($_SERVER['REQUEST_METHOD'] == 'DELETE'){
    $db = Db::getInstance();
    $db->autocommit(false);
    try {
        parse_str(file_get_contents("php://input"), $formData);
        Payment::instance()->del($formData['id']);
        $db->commit();
        echo json_encode(array('success'=> true));
    }
    catch(Exception $e) {
        $db->commit();
        echo json_encode(array('success'=> false));
        throw $e;
    }
}
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
    parse_str(file_get_contents("php://input"), $formData);
    $id = $formData['id'];
    if($formData['operation'] == 'payInvoice'){
        $db = Db::getInstance();
        $db->autocommit(false);
        try {
            $payment = Payment::instance()->getOne($id);
            if($payment['status']!=0){
                throw new Exception('Payment is paid');
            }
            $query = sprintf("UPDATE Payment SET status='1' WHERE id='%s'",
                $db->real_escape_string($id));
            if(!$db->query($query)){
                throw new Exception($db->error);
            }
            $query = sprintf("UPDATE Invoice SET status='%s' WHERE id IN
                (SELECT invoiceId FROM PaymentInvoice WHERE paymentId='%s')",
                Invoice::STATUS_PAY,
                $db->real_escape_string($id));
            if(!$db->query($query)){
                throw new Exception($db->error);
            }
            $account = Account::instance()->getOne($payment['accountId']);

            $dateTime = new DateTime($payment['payDate'].' '.$payment['payTime']);
            $date = $dateTime->format('j/n/Y');
            $time = $dateTime->format('H:i');
            Notify::mailPaidPayment($account['email'], $payment['payBank'], $date, $time, $payment['money']);
            $db->commit();
            echo json_encode(array('success'=> true));
        }
        catch (Exception $e) {
            $db->rollback();
            echo json_encode(array('success'=> false));
            throw $e;
        }

    }
    else if($formData['operation'] == 'paidTechnic'){
        $db = Db::getInstance();
        $db->autocommit(false);
        try {
            $payment = Payment::instance()->getOne($id);
            if($payment['status']!=0){
                throw new Exception('Payment is paid');
            }
            $query = sprintf("INSERT ConfigInvoice(invoiceId, status)
                SELECT Invoice.id,'0' FROM PaymentInvoice JOIN Invoice ON Invoice.id=PaymentInvoice.invoiceId
                WHERE
                    PaymentInvoice.paymentId='%s' AND Invoice.isNew=1 AND ProductId IS NULL AND Invoice.status!=1
                    AND Invoice.id NOT IN (SELECT invoiceId FROM ConfigInvoice)",
                $db->real_escape_string($id));
            if(!$db->query($query)){
                throw new Exception($db->error);
            }
            $query = sprintf("UPDATE Payment SET status='1' WHERE id='%s'",
                $db->real_escape_string($id));
            if(!$db->query($query)){
                throw new Exception($db->error);
            }
            $query = sprintf("UPDATE Invoice SET status='%s' WHERE id IN
                (SELECT invoiceId FROM PaymentInvoice WHERE paymentId='%s')",
                Invoice::STATUS_PAY,
                $db->real_escape_string($id));
            if(!$db->query($query)){
                throw new Exception($db->error);
            }
            $account = Account::instance()->getOne($payment['accountId']);

            $dateTime = new DateTime($payment['payDate'].' '.$payment['payTime']);
            $date = $dateTime->format('j/n/Y');
            $time = $dateTime->format('H:i');
            Notify::mailPaidPayment($account['email'], $payment['payBank'], $date, $time, $payment['money']);
            $db->commit();
            echo json_encode(array('success'=> true));
        }
        catch (Exception $e) {
            $db->rollback();
            echo json_encode(array('success'=> false));
            throw $e;
        }
    }
    else if($formData['operation'] == 'paidMiss'){
        $db = Db::getInstance();
        $db->autocommit(false);
        try {
            $payment = Payment::instance()->getOne($id);
            if($payment['status']!=0){
                throw new Exception('Payment is answer');
            }
            $query = sprintf("UPDATE Payment SET status='%s' WHERE id='%s'",
                Payment::STATUS_MISS,
                $db->real_escape_string($id));
            if(!$db->query($query)){
                throw new Exception($db->error);
            }
            $query = sprintf("UPDATE Invoice SET status='%s' WHERE status!=1 AND
                id IN (SELECT invoiceId FROM PaymentInvoice WHERE paymentId='%s')",
                Invoice::STATUS_WAIT,
                $db->real_escape_string($id));
            if(!$db->query($query)){
                throw new Exception($db->error);
            }
            $account = Account::instance()->getOne($payment['accountId']);

            $dateTime = new DateTime($payment['payDate'].' '.$payment['payTime']);
            $date = $dateTime->format('j/n/Y');
            $time = $dateTime->format('H:i');
            Notify::mailMissPayment($account['email'], $payment['payBank'], $date, $time, $payment['money']);
            $db->commit();
            echo json_encode(array('success'=> true));
        }
        catch (Exception $e) {
            $db->rollback();
            echo json_encode(array('success'=> false));
            throw $e;
        }
    }
    else if($formData['operation'] == 'paidNotFully'){
        $db = Db::getInstance();
        $db->autocommit(false);
        try {
            $payment = Payment::instance()->getOne($id);
            if($payment['status']!=0){
                throw new Exception('Payment is answer');
            }
            $query = sprintf("UPDATE Payment SET status='%s' WHERE id='%s'",
                Payment::STATUS_NOT_FULLY,
                $db->real_escape_string($id));
            if(!$db->query($query)){
                throw new Exception($db->error);
            }
            $query = sprintf("UPDATE Invoice SET status='%s' WHERE status!=1 AND
                id IN (SELECT invoiceId FROM PaymentInvoice WHERE paymentId='%s')",
                Invoice::STATUS_WAIT,
                $db->real_escape_string($id));
            if(!$db->query($query)){
                throw new Exception($db->error);
            }
            $account = Account::instance()->getOne($payment['accountId']);

            $dateTime = new DateTime($payment['payDate'].' '.$payment['payTime']);
            $date = $dateTime->format('j/n/Y');
            $time = $dateTime->format('H:i');
            $query = sprintf("SELECT * FROM Invoice WHERE status!=1 AND
                id IN (SELECT invoiceId FROM PaymentInvoice WHERE paymentId='%s')",
                $db->real_escape_string($id));
            $result = $db->query($query);
            if(!$result){
                throw new Exception($db->error);
            }
            $invoices = array();
            while($row = $result->fetch_assoc()){
                $row['package'] = Package::instance()->getOne($row['packageId']);
                $invoices[] = $row;
            }
            Notify::mailNotFullyPayment($account['email'], $invoices, $formData['payTrue'], $formData['moneyMiss'], nl2br($formData['info']));
            $db->commit();
            echo json_encode(array('success'=> true));
        }
        catch (Exception $e) {
            $db->rollback();
            echo json_encode(array('success'=> false));
            throw $e;
        }
    }
}